package com.bidevalution.controller.api;

import com.bidevalution.business.context.SectionMessage;
import com.bidevalution.business.context.StepStage;
import com.bidevalution.business.function.FunctionCalculator;
import com.bidevalution.business.service.*;
import com.bidevalution.controller.util.RequestUtil;
import com.bidevalution.controller.vo.BeSectionDataVO;
import com.bidevalution.controller.vo.BeSectionLayoutVO;
import com.bidevalution.dao.entity.*;
import com.bidevalution.service.layout.ColumnHeader;
import com.bidevalution.service.layout.LayoutCode;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.context.SpringContextUtil;
import com.bidevalution.support.exception.BizException;
import com.bidevalution.support.util.StringUtil;
import com.google.common.collect.Maps;
import com.qtp.common.core.TSUser;
import com.qtp.common.data.RedisAccess;
import com.qtp.core.model.Response;
import com.qtp.core.util.GsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @修改记录
 * 2020-03-26 whc 提交状态判断修改
 * 2020-04-07 whc ZTKP-3481 添加终止项目
 * 2020-04-13 胡一奇 需求 ZTKP-3829 技术标评分主页面展示评审明细
 */

/**
 * 评审环节数据页面渲染和评审数据查询
 *
 * @author daizhifeng
 * @date 2019年9月12日 下午4:27:56
 * @version V2.0
 * 2020-03-31 夏云飞 需求 二阶段项目提前计算改造
 */
@Log4j2
@RestController
@RequestMapping("/beSectionLayout")
@Api(tags = "标段环节布局")
public class BeSectionLayoutController extends BaseController {
	@Autowired
	private BeSectionLayoutService beSectionLayoutService;
	@Autowired
	private BeSectionStepService beSectionStepService;
	@Autowired
	private BeSectionParameterService beSectionParameterService;
	@Autowired
	private BeSectionStepJobService beSectionStepJobService;
	@Autowired
	private BeSectionInfoService beSectionInfoService;
	@Autowired
	private BeSectionExpertInfoService beSectionExpertInfoService;
	@Autowired
	private BeSectionExpertProgressService beSectionExpertProgressService;
	@Autowired
	private BeSectionButtonService beSectionButtonService;
	@Autowired
	private BeEvalutionOutcomeService beEvalutionOutcomeService;
	@Autowired
	private BeSectionColumnService beSectionColumnService;
	@Autowired
	private BeEvalutionColumnService beEvalutionColumnService;
	@Autowired
	private BeSectionMessageService beSectionMessageService;
	@Autowired
	private TempBeEvalutionOutcomeService tempBeEvalutionOutcomeService;
	@Autowired
	private BeSectionEnterpriseService beSectionEnterpriseService;
	@Value("${IS_RETAIN_RESULT}")
	private String isRetainResult;
	private Logger log = Logger.getLogger(getClass());

	private static final String LAYOUT_CODE_LEFT = "Left";

	@GetMapping("/getBeSectionLayout")
	@ApiOperation(value = "查询标段环节布局数据", notes = "查询标段环节布局", response = BeSectionLayoutVO.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionStepId", value = "环节ID", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "layoutCode", value = "布局代码", required = true, dataType = "String", paramType = "query") })
	public Response<BeSectionLayoutVO> getBeSectionLayout(String sectionStepId, String layoutCode) {
		try {
			String userGuid = RequestUtil.getHeader("userGuid");
			TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
//			TSUser tsUser = new TSUser();
//			tsUser.setUserGuid("1111111111111111111");
//			tsUser.setLoginName("sh01");
			if (tsUser == null) {
				return Response.fail("获取专家账号登录信息失败");
			}


			BeSectionStep beSectionStep = beSectionStepService.getSectionStepBySeqId(sectionStepId);
			if (beSectionStep == null) {
				throw new Exception("未查询到该标段环节信息");
			}
			BeSectionExpertInfo beSectionExpertInfo = beSectionExpertInfoService
					.selectByLoginName(beSectionStep.getSectionId(), tsUser.getLoginName());
			if (beSectionExpertInfo == null) {
				throw new Exception("当前用户不是该标段专家");
			}
			// 添加评审专家到评审过程表中
			BeSectionExpertProgress beSectionExpertProgress = beSectionExpertProgressService.selectByKey(sectionStepId,
					beSectionExpertInfo.getSeqId());
			if (beSectionExpertProgress == null) {
				throw new Exception("专家审核环节数据不存在");
			}
			BeSectionLayoutVO bynamicDataTable = new BeSectionLayoutVO();
			BeSectionLayout beSectionLayout = beSectionLayoutService.getBeSectionLayout(sectionStepId, layoutCode);
			if (beSectionLayout == null || StringUtils.isEmpty(beSectionLayout.getConfig())) {
				log.error(layoutCode+"未查询到标段环节配置数据");
				return Response.ok(bynamicDataTable);
			}

			bynamicDataTable.setLayoutText(beSectionLayout.getLayoutText());
			bynamicDataTable.setLayoutCode(layoutCode);
			// 生成按钮区域配置
			if (beSectionLayout.getLayoutCode().equals(LayoutCode.Header.name())) {
				// 把头部区域的数据加入到返回值中
				bynamicDataTable.getControlList().addAll(beSectionButtonService.getFormControlList(beSectionExpertInfo,
						beSectionStep.getSectionId(), sectionStepId, layoutCode));
				if (bynamicDataTable.getControlList().size() == 0) {
					return Response.ok(bynamicDataTable);
				}
			} else {
				// 判断是否存在现实列配置
				List<ColumnHeader> columnHeaderList = beSectionColumnService.getColumnHeaderList(beSectionExpertInfo,
						sectionStepId, beSectionLayout, !"1".equals(beSectionExpertProgress.getIsFinish()));
				// 如果字段列不存在，则返回结果
				if (columnHeaderList.size() == 0) {
					return Response.ok(bynamicDataTable);
				}
				// 表格行单击事件
				bynamicDataTable.setClickFunction(beSectionLayout.getClickFunction());
				bynamicDataTable.getTableHead().addAll(columnHeaderList);

			}

			/*Begin 2020-04-13 胡一奇 需求 ZTKP-3829 技术标评分主页面展示评审明细*/
			List<ColumnHeader> headers = bynamicDataTable.getTableHead();
			Map<Integer, List<ColumnHeader>> columnHeaderMapping = new HashMap<>(4);
			int index = 0;
			for(ColumnHeader header:headers) {
				if(ColumnHeader.ColumnType.DYNAMIC.getCode().equals(header.getColumnType())) {
					String beanId = header.getCode();
					DynamicColumnDataSource dcds = (DynamicColumnDataSource) SpringContextUtil.getBean(beanId);
					List<ColumnHeader> dcList = dcds.getDynamicColumnHead(beSectionStep, header);
					if(dcList!=null) {
						columnHeaderMapping.put(index, dcList);
					}
				}
				index++;
			}
			for(Map.Entry<Integer, List<ColumnHeader>> entry:columnHeaderMapping.entrySet()) {
				headers.remove(entry.getKey().intValue());
				headers.addAll(entry.getKey(), entry.getValue());
			}
			/*End 2020-04-13 胡一奇 需求 ZTKP-3829 技术标评分主页面展示评审明细*/
			log.info("环节初始化返回数据，环节id[" + sectionStepId + "],专家名称[" + tsUser.getLoginName() + "]环节布局["
					+ bynamicDataTable.getLayoutCode() + "],字段列表[" + GsonUtil.toJson(bynamicDataTable.getTableHead()) + "],控件列表["
					+ GsonUtil.toJson(bynamicDataTable.getControlList()) + "]");
			return Response.ok(bynamicDataTable);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Response.fail(e.getMessage());
		}
	}

	@GetMapping("/getBeSectionData")
	@ApiOperation(value = "查询标段环节布局数据", notes = "查询标段环节布局数据", response = BeSectionDataVO.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionStepId", value = "环节ID", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "layoutCode", value = "布局代码", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "condition", value = "查询条件:json字符串", dataType = "String", paramType = "query") })
	public Response<BeSectionDataVO> getBeSectionData(String sectionStepId, String layoutCode, String condition) {
		try {

			long start = System.currentTimeMillis();
			String userGuid = RequestUtil.getHeader("userGuid");
			TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
			// TODO 测试
//			TSUser tsUser = new TSUser();
//			tsUser.setUserGuid("1111111111111111111");
//			tsUser.setLoginName("dzf02");
			if (tsUser == null) {
				return Response.fail("获取专家账号登录信息失败");
			}
			BeSectionStep beSectionStep = beSectionStepService.getSectionStepBySeqId(sectionStepId);
			if (beSectionStep == null) {
				throw new Exception("未查询到该标段环节信息");
			}
			BeSectionExpertInfo beSectionExpertInfo = beSectionExpertInfoService
					.selectByLoginName(beSectionStep.getSectionId(), tsUser.getLoginName());
			if (beSectionExpertInfo == null) {
				throw new Exception("当前用户不是该标段专家");
			}

			BeSectionExpertProgress beSectionExpertProgress = beSectionExpertProgressService
					.selectByKey(beSectionStep.getSeqId(), beSectionExpertInfo.getSeqId());
			if (beSectionExpertProgress == null) {
				throw new Exception("专家审核环节数据不存在");
			}
			BeSectionDataVO beSectionDataVO = new BeSectionDataVO();
			// 布局代码
			beSectionDataVO.setLayoutCode(layoutCode);
			log.info("layoutCode:>>>>>>>>>>>>>>"+layoutCode);
			if (layoutCode.equals(LayoutCode.Header.name())) {
				return Response.ok(beSectionDataVO);
			}
			BeSectionLayout beSectionLayout = beSectionLayoutService.getBeSectionLayout(sectionStepId, layoutCode);
			if (beSectionLayout == null || StringUtils.isEmpty(beSectionLayout.getConfig())) {
				log.error("标段环节未配置数据:"+layoutCode);
				return Response.ok(beSectionDataVO);
			}
			log.info("速度测试，方法getBeSectionData查询基本信息（ms）"+(System.currentTimeMillis()-start));
			// 查询布局数据
			start = System.currentTimeMillis();
			//加锁
			/*boolean lock = RedisLockTool.getDistributedLock(RedisUtil.getJedis(), INIT_DATA_LOCK + beSectionStep.getSeqId() + layoutCode , beSectionStep.getSeqId(), 60 * 5);
			if (lock) {*/
			List<Map<String, Object>> dataList = null;
			synchronized ((beSectionStep.getSeqId() + layoutCode).intern()) {
				log.info("锁环节id" + beSectionStep.getSeqId() + "环节布局" + layoutCode + "专家名称" + tsUser.getLoginName());
				dataList = computeDataList(tsUser, beSectionStep, beSectionExpertProgress,
						beSectionExpertInfo, beSectionLayout,
						StringUtils.isEmpty(condition) ? null : GsonUtil.jsonToMapWithGson(condition));
				List<BeEvalutionColumn> columnList = beEvalutionColumnService.selectList();
				// 在执行环节布局数据查询完成之后执行行数据计算行数据
				//			for (Map<String, Object> dataMap : dataList) {
				//				beSectionStepJobService.callRowJob(sectionStepId, beSectionExpertProgress.getSubmitCode(),
				//						beSectionExpertInfo.getSeqId(),layoutCode, StepStage.Before, dataMap);
				//				log.info("行任务计算结果:" + dataMap);
				//			}

				// 添加数据到返回对象
				beSectionDataVO.getTableBody().addAll(dataList);
				// 数据初始化,保存到专家评审明细结果表be_evalution_outcome中
				//目前布局为Left的都是环节信息数据，不需要保存到评审表，过滤这部分脏数据
				log.info("速度测试，方法getBeSectionData调用computeDataList方法（ms）" + (System.currentTimeMillis() - start));
				start = System.currentTimeMillis();
				if (!LAYOUT_CODE_LEFT.equals(layoutCode)) {
					saveInitData(beSectionStep, beSectionExpertInfo.getSeqId(), beSectionExpertProgress, layoutCode, dataList,
							beSectionColumnService.getColumnHeaderList(beSectionExpertInfo, beSectionStep.getSeqId(),
									beSectionLayout, !"1".equals(beSectionExpertProgress.getIsFinish())),
							columnList);
				}
			}
//			}
			//加锁锁环节
			synchronized (beSectionStep.getSeqId().intern()) {
				//杭州地区目前重评之后需要将专家上次的评审内容保留，加个开关
				if (Constants.TRUE.equals(isRetainResult) && Constants.ONE.equals(beSectionStep.getRetentionReviewData())) {
					List<BeSectionStep> childSectionSteps = null;
					if (Constants.ZERO.toString().equals(beSectionStep.getParentCode())) {
						childSectionSteps = beSectionStepService.queryChildSectionSteps(beSectionStep.getSectionId(), beSectionStep.getStepCode());
					}
					if (!LAYOUT_CODE_LEFT.equals(layoutCode) && (childSectionSteps == null || childSectionSteps.isEmpty())) {
						//查询此环节评审临时表是否有数据
						if (tempBeEvalutionOutcomeService.queryListById(beSectionStep.getSectionId(), beSectionStep.getSeqId(), beSectionExpertInfo.getSeqId()).size() > Constants.ZERO) {
							//查询当前环节的子环节并复制专家上一次评审结果
							List<BeSectionStep> beSectionSteps = beSectionStepService.getAllChildSectionStep(beSectionStep.getSectionId(), beSectionStep.getStepCode());
							if (beSectionSteps != null && !beSectionSteps.isEmpty()) {
								for (BeSectionStep _beSectionStep : beSectionSteps) {
									System.out.println("重评初始化数据，插入当前环节子环节[" + _beSectionStep.getStepCode() + "]");
									beEvalutionOutcomeService.insertSyncResult(beSectionStep.getSectionId(), _beSectionStep.getSeqId(), beSectionExpertInfo.getSeqId());
									//删除临时表数据
									tempBeEvalutionOutcomeService.deleteListById(beSectionStep.getSectionId(), _beSectionStep.getSeqId(), beSectionExpertInfo.getSeqId());
								}
							}
							System.out.println("重评初始化数据，更新当前环节[" + beSectionStep.getStepCode() + "]");
							beEvalutionOutcomeService.updateSyncResult(beSectionStep.getSectionId(), beSectionStep.getSeqId(), beSectionExpertInfo.getSeqId());
							//删除临时表数据
							tempBeEvalutionOutcomeService.deleteListById(beSectionStep.getSectionId(), beSectionStep.getSeqId(), beSectionExpertInfo.getSeqId());
							beSectionDataVO.getTableBody().removeAll(dataList);
							beSectionDataVO.getTableBody().addAll(computeDataList(tsUser, beSectionStep, beSectionExpertProgress,
									beSectionExpertInfo, beSectionLayout,
									StringUtils.isEmpty(condition) ? null : GsonUtil.jsonToMapWithGson(condition)));
						}
					}
				}
			}

			/*Begin 2020-04-13 胡一奇 需求 ZTKP-3829 技术标评分主页面展示评审明细*/
			List<ColumnHeader> headers = beSectionColumnService.getColumnHeaderList(beSectionExpertInfo,
					sectionStepId, beSectionLayout, !"1".equals(beSectionExpertProgress.getIsFinish()));
			for(ColumnHeader header:headers) {
				if(ColumnHeader.ColumnType.DYNAMIC.getCode().equals(header.getColumnType())) {
					String beanId = header.getCode();
					DynamicColumnDataSource dcds = (DynamicColumnDataSource) SpringContextUtil.getBean(beanId);
					dcds.getDynamicColumnData(beSectionStep, header, beSectionDataVO.getTableBody(), beSectionExpertInfo.getSeqId());
				}
			}
			/*End 2020-04-13 胡一奇 需求 ZTKP-3829 技术标评分主页面展示评审明细*/
			log.info("速度测试，方法getBeSectionData初始化页面数据（ms）"+(System.currentTimeMillis()-start));
			log.info("环节初始化返回数据，环节id[" + sectionStepId + "],专家名称[" + tsUser.getLoginName() + "]环节布局["
					+ beSectionDataVO.getLayoutCode() + "],数据列表[" + GsonUtil.toJson(beSectionDataVO.getTableBody()) + "]");
			return Response.ok(beSectionDataVO);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Response.fail(e.getMessage());
		} /*finally {
			//释放锁标识
			RedisLockTool.releaseDistributedLock(RedisUtil.getJedis(), INIT_DATA_LOCK + sectionStepId + layoutCode, sectionStepId);
		}*/
	}

	/**
	 * 生成数据 @param @param tsUser @param @param beSectionStep @param @param
	 * beSectionExpertProgress @param @param beSectionExpertInfo @param @param
	 * layoutCode @param @param conditionMap @param @return @param @throws Exception
	 * 参数 @return List<Map<String,Object>> 返回类型 @throws
	 */
	public List<Map<String, Object>> computeDataList(TSUser tsUser, BeSectionStep beSectionStep,
													 BeSectionExpertProgress beSectionExpertProgress, BeSectionExpertInfo beSectionExpertInfo,
													 BeSectionLayout beSectionLayout, Map<String, Object> conditionMap) throws Exception {

		// 获取标段信息
		BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(beSectionStep.getSectionId());
		if (beSectionInfo == null) {
			throw new Exception("未查询到标段数据");
		}

		BeSectionDataVO beSectionDataVO = new BeSectionDataVO();
		beSectionDataVO.setLayoutCode(beSectionLayout.getLayoutCode());
		// 获取字段配置信息
		List<ColumnHeader> columnHeaderList = beSectionColumnService.getColumnHeaderList(beSectionExpertInfo,
				beSectionStep.getSeqId(), beSectionLayout, !"1".equals(beSectionExpertProgress.getIsFinish()));

		// 获取配置的sql语句
		String sqlConfig = beSectionLayout.getConfig();
		// 判断sql不为空
		if (!StringUtils.isEmpty(sqlConfig)) {
			sqlConfig = sqlConfig.trim();
			Map<String, Object> env = Maps.newHashMap();
			// 将标段参数值放入到sql语句的公式计算参数中
			for (BeSectionParameter beSectionParameter : beSectionParameterService
					.selectList(beSectionStep.getSectionId())) {

				env.put("$PARAM_" + beSectionParameter.getParamId(), beSectionParameter.getParamValue());
			}
			/****************执行环节执行之前的任务***********************/
			//执行子环节
			long start = System.currentTimeMillis();
			beSectionStepJobService.callStepUnionJob(beSectionStep, beSectionExpertProgress.getSubmitCode(),
					beSectionExpertInfo.getSeqId(), beSectionLayout.getLayoutCode(),StepStage.Before);
			//执行当前环节任务
			beSectionStepJobService.callStepJob(beSectionStep, beSectionExpertProgress.getSubmitCode(), StepStage.Before,
					beSectionExpertInfo.getSeqId(), beSectionLayout.getLayoutCode());
			log.info("速度测试，方法computeDataList环节任务执行时间（ms）"+(System.currentTimeMillis()-start));
			List<BeSectionStep> preSectionStepList = beSectionStepService.getPreStepList(beSectionStep);
			List<BeSectionStep> nextSectionStepList = beSectionStepService.getNextStepList(beSectionStep);
			start = System.currentTimeMillis();
			env.put("sectionStepId", beSectionStep.getSeqId());
			env.put("expertId", beSectionExpertInfo.getSeqId());
			env.put("userId", tsUser.getUserGuid());
			env.put("sectionId", beSectionStep.getSectionId());
			env.put("tdProjectId", beSectionInfo.getTdProjectid());
			env.put("submitCode", beSectionExpertProgress.getSubmitCode());
			env.put("layoutCode",beSectionLayout.getLayoutCode());
			// sql语句公式计算
			if (sqlConfig.toLowerCase().startsWith("{ael[")) {
				sqlConfig = sqlConfig.substring(5, sqlConfig.length() - 2);
				log.info("sqlConfig公式解析结果:" + sqlConfig);
				sqlConfig = FunctionCalculator.computeAviator(sqlConfig, env);
			} else if (sqlConfig.toLowerCase().startsWith("{mel[")) {
				sqlConfig = sqlConfig.substring(5, sqlConfig.length() - 2);
				log.info("sqlConfig公式解析结果:" + sqlConfig);
				sqlConfig = FunctionCalculator.computeMVEL(sqlConfig, env);
			}
			log.info("速度测试，方法computeDataList sql公式计算执行时间（ms）"+(System.currentTimeMillis()-start));
			// 获取sql语句的参数名和参数值
			Map<String, Object> sqlParamMap = new HashMap<String, Object>();
			sqlParamMap.put("sectionStepId", beSectionStep.getSeqId());
			sqlParamMap.put("expertId", beSectionExpertInfo.getSeqId());
			sqlParamMap.put("userId", tsUser.getUserGuid());
			sqlParamMap.put("sectionId", beSectionStep.getSectionId());
			sqlParamMap.put("tdProjectId", beSectionInfo.getTdProjectid());
			sqlParamMap.put("stepCode", beSectionStep.getStepCode());
			sqlParamMap.put("submitCode", beSectionExpertProgress.getSubmitCode());
			sqlParamMap.put("layoutCode",beSectionLayout.getLayoutCode());
			if(preSectionStepList.size()>0) {
				sqlParamMap.put("preStepId",preSectionStepList.get(preSectionStepList.size() - 1).getSeqId());
			}
			if(nextSectionStepList.size()>0) {
				sqlParamMap.put("nextStepId",nextSectionStepList.get(nextSectionStepList.size() - 1).getSeqId());
			}
			if (conditionMap != null) {
				sqlParamMap.putAll(conditionMap);
			}
			// 获取数据
			List<Map<String, Object>> dataList = beSectionLayoutService.getDataList(sqlConfig, sqlParamMap);

			// 添加数据到返回对象
			return getData(beSectionExpertInfo, beSectionStep, dataList, columnHeaderList, beSectionLayout,
					beSectionExpertProgress.getSubmitCode());
		}
		return null;
	}

	/**
	 * @throws Exception
	 *@return void 返回类型 @throws
	 */
	public void saveInitData(BeSectionStep beSectionStep, String expertId,
							 BeSectionExpertProgress beSectionExpertProgress, String layoutCode, List<Map<String, Object>> dataList,
							 List<ColumnHeader> columnHeaderList, List<BeEvalutionColumn> columnList) throws Exception {
		// 保存数据到评审结果表中
		if (!StringUtils.isEmpty(beSectionStep.getStepUrl())) {
			// 查询环节数据是否存在
			int cntInteger = beEvalutionOutcomeService.selectCount(beSectionStep.getSeqId(), expertId,
					layoutCode);
			if (dataList.size() != cntInteger) {
                System.out.println("初始化环节数据，环节["+beSectionStep.getStepName()+"]");
				// 初始化新增环节数据
				beEvalutionOutcomeService.save(dataList, columnHeaderList, beSectionStep, expertId, layoutCode,
						beSectionExpertProgress.getSubmitCode(), "0",false, columnList);
			}
		}
	}

	/**
	 * 获取数据值
	 *
	 * @return
	 * @throws Exception
	 */
	public List<Map<String, Object>> getData(BeSectionExpertInfo beSectionExpertInfo, BeSectionStep beSectionStep,
											 List<Map<String, Object>> dataList, List<ColumnHeader> columnHeaderList, BeSectionLayout beSectionLayout,
											 String submitCode) throws Exception {

		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if(dataList == null) {
			return resultList;
		}
		Map<String, Object> returnData = null;
		String defaultValue = "";
		String formulaConfig = "";
		Map<String, Object> env = null;
		// 数据查询
		int i = 0;
		for (Map<String, Object> dataMap : dataList) {
			returnData = new HashMap<String, Object>();
			for (ColumnHeader columnHeader : columnHeaderList) {
				if (columnHeader.getColumnType().equals("LINENUMBER")) {
					i++;
					returnData.put(columnHeader.getCode(), i);
					continue;
				}

				// 初始化默认值,替换默认值中的可变参数
				defaultValue = columnHeader.getDefaultValue();
				if (!StringUtils.isEmpty(defaultValue)) {
					for (BeSectionParameter beSectionParameter : beSectionParameterService
							.selectList(beSectionStep.getSectionId())) {
						defaultValue = defaultValue.replaceAll("\\{PARAM_" + beSectionParameter.getParamId() + "\\}",
								beSectionParameter.getParamValue());
					}
					returnData.put(columnHeader.getCode(), defaultValue);
				} else {
					returnData.put(columnHeader.getCode(), "");
				}

				// 非公式计算
				for (Entry<String, Object> entry : dataMap.entrySet()) {
					if (entry.getKey().toLowerCase().equals(columnHeader.getCode().toLowerCase())) {
						returnData.put(columnHeader.getCode(),
								StringUtil.toString(dataMap.get(columnHeader.getCode())));
						break;
					}
				}
			}
			//列计算公式
			for (ColumnHeader columnHeader : columnHeaderList) {
				// 计算公司
				formulaConfig = columnHeader.getFormulaConfig();

				if (!StringUtils.isEmpty(formulaConfig)) {
					// 将变量赋值
					// 每行在字段数据作为参数传入到公式计算
					env = new HashMap<String, Object>();
					// 评标参数放入到计算公式的参数中去
					for (BeSectionParameter beSectionParameter : beSectionParameterService
							.selectList(beSectionStep.getSectionId())) {
						env.put("$PARAM_" + beSectionParameter.getParamId(),
								StringUtil.toString(beSectionParameter.getParamValue()));
					}

					for (Entry<String, Object> entry : dataMap.entrySet()) {
						env.put("$" + entry.getKey(), StringUtil.toString(entry.getValue()));
					}
					env.put("$expertId", beSectionExpertInfo.getSeqId());
					env.put("$sectionStepId", beSectionStep.getSeqId());
					env.put("$EXPERT_TYPE", beSectionExpertInfo.getExpertType());
					env.put("$IS_MANAGER", beSectionExpertInfo.getIsManager());
					env.putAll(returnData);
					// 公式计算结果
					if (formulaConfig.toLowerCase().startsWith("{mel[")) {
						formulaConfig = formulaConfig.substring(5, formulaConfig.length() - 2);
						returnData.put(columnHeader.getCode(), FunctionCalculator.computeMVEL(formulaConfig, env));
					} else if(formulaConfig.toLowerCase().startsWith("{ael[")){
						formulaConfig = formulaConfig.substring(5, formulaConfig.length() - 2);
						returnData.put(columnHeader.getCode(), FunctionCalculator.computeAviator(formulaConfig, env));
					}
				}
			}
			resultList.add(returnData);
		}
		return resultList;
	}

    /**
     * @修改记录
     * @version 1.0
     * @author lhl
     * @date 2020-04-21 10:32
     * 1、检查是否存在表决
     */
	@GetMapping("/findUnFinishList")
	@ApiOperation(value = "查询计算还未执行完成任务", notes = "下一步判断", response = BeSectionDataVO.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionId", value = "sectionId", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "sectionStepId", value = "sectionStepId", required = true, dataType = "String", paramType = "query")})
	public Response<String> findUnFinishList(@RequestParam("sectionId")String sectionId,@RequestParam("sectionStepId")String sectionStepId) {
		try {
			/** begin:2020-03-31 夏云飞 需求 二阶段项目提前计算改造 */
			if (Constants.ONE.equals(beSectionInfoService.getBeSectionInfoById(sectionId).getIsTwoStage())) {
				//二阶段项目如果导入了技术标则技术标之前的环节需要控制提前计算
				BeSectionEnterprise beSectionEnterprise = new BeSectionEnterprise();
				beSectionEnterprise.setSectionId(sectionId);
				//2表示技术标导入成功
				beSectionEnterprise.setImportResult(Constants.TWO);
				BeSectionStepJob beSectionStepJob = new BeSectionStepJob();
				beSectionStepJob.setSectionId(sectionId);
				beSectionStepJob.setIsFinish(Constants.IS_FINISH);
				beSectionStepJob.setIsAdvanceExecute(Constants.IS_ADVANCE_EXECUTE);
				beSectionStepJob.setIsBusinessBefore(Constants.ONE);
				if (beSectionEnterpriseService.queryByCondition(beSectionEnterprise).size() > 0
						&& beSectionStepJobService.findUnFinishList(beSectionStepJob).size() > 0) {
					throw new BizException("二阶段项目评审流程提前计算的任务未完成，请等待计算完成再操作");
				}
			} else {
				//不是二阶段的项目都需要控制提前计算
				if (beSectionStepJobService.findUnFinishList(sectionId).size() > 0) {
				throw new BizException("评审流程提前计算的任务未完成，请等待计算完成再操作");
			}
			}
			/** end:2020-03-31 夏云飞 需求 二阶段项目提前计算改造 */
			BeSectionStep beSectionStep = beSectionStepService.selectByPrimaryKey(sectionStepId);
			if(beSectionStep != null) {
				if(beSectionStepJobService.findUnFinishCnt(sectionStepId)>0) {
					beSectionInfoService.checkTermination(sectionId);
					// 检查是否存在表决
					beSectionInfoService.checkExistsVote(sectionId);
					throw new BizException("请先完成前面的环节评审");
				}
				for(BeSectionStep sectionStep:beSectionStepService.getAllChildSectionStep(beSectionStep.getSectionId(), beSectionStep.getParentCode())) {
					if(beSectionStepJobService.findUnFinishCnt(sectionStep.getSeqId())>0) {
						beSectionInfoService.checkTermination(sectionId);
						//检查是否存在表决
						beSectionInfoService.checkExistsVote(sectionId);
						throw new BizException("请先完成前面的环节评审");
					}
				}
//				if(!"1".equals(beSectionStep.getIsActive())) {
//					throw new BizException("请先评审完成前面的环节");
//				}
				//是否存在替补消息
				BeSectionMessage beSectionMessage = beSectionMessageService.selectBySectionStepId(sectionStepId,SectionMessage.NextStepRestrict);
				log.info(beSectionMessage==null?">>>>>>>>>>>>>>>>>>>>>>>>>>>>>":beSectionMessage.getMessage());
				if(beSectionMessage != null && !StringUtils.isEmpty(beSectionMessage.getMessage())) {
					throw new BizException(beSectionMessage.getMessage());
				}
			}
			
			
			
		}catch (Exception e) {
			return Response.ok(e.getMessage());
		}
		return Response.ok("1");
	}

	@GetMapping("/checkFindUnFinishList")
	@ApiOperation(value = "查询计算还未执行完成任务", notes = "当前环节是否计算完成判断，暂时用于重评", response = BeSectionDataVO.class)
//	@ApiImplicitParams({
//			@ApiImplicitParam(name = "sectionId", value = "sectionId", required = true, dataType = "String", paramType = "query")})
	public Response<List<BeSectionStepJob>> findUnFinishList(BeSectionStepJob beSectionStepJob) {
		List<BeSectionStepJob> list = beSectionStepJobService.findUnFinishList(beSectionStepJob);
		return Response.ok(list);
	}
}
